package cn.fl.risknew.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risknew.condition.RskUsrOrgRoleQC;
import cn.fl.risknew.dto.RskUsrOrgRoleDTO;
import cn.fl.risknew.condition.RskUsrCstRQueryCondition;
import cn.fl.risknew.dto.RskUsrCstRDTO;
import cn.fl.risknew.service.IRskUsrCstRNewApiService;
import cn.fl.risknew.service.IRskUsrCstRNewService;
import cn.fl.risknew.service.IRskUsrOrgRoleNewApiService;
import cn.fl.risknew.transform.RskUsrCstRVOTransform;
import cn.fl.risknew.vo.RskUsrCstRVO;

/**
 * @Description: 催收员客户关系表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class RskUsrCstRNewServiceImpl implements IRskUsrCstRNewService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(RskUsrCstRNewServiceImpl.class);
	
	@Autowired
	private IRskUsrCstRNewApiService rskUsrCstRNewApiService;
	@Autowired
	private IRskUsrOrgRoleNewApiService rskUsrOrgRoleNewApiService;

	@Override
	public RskUsrCstRVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		RskUsrCstRDTO dto = this.rskUsrCstRNewApiService.selectRskUsrCstRById(id);
		return RskUsrCstRVOTransform.toVO(dto);
	}

	@Override
    public Long add(RskUsrCstRVO entity) throws BaseException{
        if(null == entity) return null;
        return this.rskUsrCstRNewApiService.addRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
    }

    @Override
    public boolean addR(RskUsrCstRVO entity) throws BaseException{
        if(null == entity) return false;
        return this.rskUsrCstRNewApiService.batchAddRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
    }

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.rskUsrCstRNewApiService.removeRskUsrCstRByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(RskUsrCstRVO entity) throws BaseException{
		if(null == entity) return false;
		return this.rskUsrCstRNewApiService.modifyRskUsrCstR(RskUsrCstRVOTransform.toDTO(entity));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        RskUsrCstRQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new RskUsrCstRQueryCondition());
        }
		condition=(RskUsrCstRQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.rskUsrCstRNewApiService.searchRskUsrCstRListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList((List<RskUsrCstRDTO>)page.getResultList());
            //this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<RskUsrCstRVO> searchList(RskUsrCstRQueryCondition condition) throws BaseException{
		if(null == condition) condition=new RskUsrCstRQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList(this.rskUsrCstRNewApiService.searchRskUsrCstRList(condition));
		this.setDictData(voList);
		return voList;
	}

    /*********************************
     * 查询每个催收员的任务数
     * @param condition
     * @return
     * @throws BaseException
     ********************************/
    public List<RskUsrCstRVO> searchTaskQtyByUsr(RskUsrCstRQueryCondition condition) throws BaseException{
        if(null == condition) condition=new RskUsrCstRQueryCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        List<RskUsrCstRVO> voList=RskUsrCstRVOTransform.toVOList(this.rskUsrCstRNewApiService.searchRskUsrCstRList(condition));
        this.setDictData(voList);
        return voList;
    }

    /*******************************
     * 查询分配催收任务客户列表
     * @param page
     * @return
     * @throws BaseException
     *******************************/
    @SuppressWarnings("unchecked")
	@Override
    public Pager searchUsrList(Pager page) throws BaseException {
//        RskUsrOrgRoleQC condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new RskUsrOrgRoleQC());
        }
//        condition=(RskUsrOrgRoleQC)page.getCondition();
//        // 先查询当前人的角色 如果是list 类型 目前没有多个角色的人存在，所以他们的角色是一致的
//        List<RskUsrOrgRoleDTO> byUsrId = rskUsrOrgRoleApiService.getByUsrId(CurrentThreadContext.getCurrentUserId());
//        if(CollectionUtils.isEmpty(byUsrId)){
//            BaseLogUtils.error(logger,"searchCstList","查不到当前用户所负责的区域");
//            return null;
//        }
//        //设置评审人员角色
//        Long currentRoleId = byUsrId.get(0).getRoleId();
//        String currentOrgCd = byUsrId.get(0).getOrgCd();
//        List<String> orgCdList = new ArrayList<>();
//        if(RiskConstant.ROLE_CODE_REPAYMENT_G_MANAGER.equals(String.valueOf(currentRoleId)) || RiskConstant.ROLE_CODE_REPAYMENT_CAR_FIN_MANAGER.equals( String.valueOf(currentRoleId) ) ){
//            // 总经理和汽车金融主管可以分配任务给 贷后事业部 及 信审中心 成员
//            // 查全部
//        }else if(RiskConstant.ROLE_CODE_REPAYMENT_MANAGER.equals(String.valueOf(currentRoleId))){
//            // 各省贷后事业部经理
//            // 查询 各省贷后事业部分公司成员
//            for (RskUsrOrgRoleDTO rskUsrOrgRoleDTO : byUsrId) {
//                orgCdList.add(rskUsrOrgRoleDTO.getOrgCd());
//            }
//            orgCdList.add(String.valueOf(currentOrgCd));
//        }else{ //信审中心催收管理部经理 或者 信审中心总经理
//            // 查询所有 信审中心成员
//            ArrayList<String> roleIds = new ArrayList<>();
//            roleIds.add("10030"); //信审员
//            roleIds.add("10028"); //信审中心总经理
//            roleIds.add("10031"); //催收管理部经理
//            roleIds.add("10029"); //业务审核部经理
//            condition.setRoleIdList(roleIds);
//        }
//        condition.setOrgCdList(orgCdList);
        page = this.rskUsrOrgRoleNewApiService.searchListPage(page);
        if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<RskUsrOrgRoleDTO> dtoList=(List<RskUsrOrgRoleDTO>)page.getResultList();
            List<Long> cstIdList=new ArrayList<>(dtoList.size());
            for(RskUsrOrgRoleDTO sysUsrDTO:dtoList){
                cstIdList.add(sysUsrDTO.getUsrId());
            }
            //查询催收用户的客户数（任务数）
            RskUsrCstRQueryCondition usrCstRQueryCondition=new RskUsrCstRQueryCondition();
            usrCstRQueryCondition.setCstIdList(cstIdList);
            List<RskUsrCstRDTO> rList=this.rskUsrCstRNewApiService.searchTaskQtyByUsr(usrCstRQueryCondition);
            Map<Long,String> qtyMap=null;
            if(CollectionUtils.isNotEmpty(rList)){
                qtyMap=new HashMap<>(rList.size());
                for(RskUsrCstRDTO cstRDTO:rList){
                    qtyMap.put(cstRDTO.getUsrId(),cstRDTO.getCstQty()+";"+cstRDTO.getOveAmountSum());
                }
            }
            //拼装结果集
            List<RskUsrCstRVO> voList=new ArrayList<RskUsrCstRVO>(dtoList.size());
            RskUsrCstRVO vo=null;
            String value=null;
            String oveAmountSum=null;
            for(RskUsrOrgRoleDTO sysUsrDTO:dtoList){
                vo=new RskUsrCstRVO();
                vo.setUsrId(sysUsrDTO.getUsrId());
                vo.setUsrNm(sysUsrDTO.getName());
                vo.setAccount(sysUsrDTO.getAccount());
                if(qtyMap!=null&&qtyMap.containsKey(sysUsrDTO.getUsrId())){
                	value=qtyMap.get(sysUsrDTO.getUsrId());
                    vo.setTaskQty(Long.valueOf(value.split(";")[0]));
                    oveAmountSum=value.split(";")[1];
                    if(StringUtils.isNotEmpty(oveAmountSum)&&!"null".equals(oveAmountSum)) {
                   	 vo.setOveAmountSum(Long.valueOf(oveAmountSum));
                   }
                }else{
                    vo.setTaskQty(0L);
                    vo.setOveAmountSum(0l);
                }
                voList.add(vo);
            }
            page.setResultList(voList);
        }
        return page;
    }

    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<RskUsrCstRVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		/*Map<String, String> _CdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, RskUsrCstRConstant.CODE_CD);
		for(RskUsrCstRVO vo:voList){
			if (_CdMap != null && _CdMap.containsKey(vo.getCd())) {
            	vo.setCdNm(_CdMap.get(vo.getCd()));
        	}	
		}*/
	}

	@Override
	public void addCst2Usr(Long usrId, List<Long> cstIdList, String inWay, Long currentUserId) {
		this.rskUsrCstRNewApiService.addCst2Usr(usrId,cstIdList,inWay,currentUserId);
	}
}
